﻿using System.Web.Mvc;
using ManagedUIFlow.Infrastructure.Services;
using ManagedUIFlow.Model;

namespace ManagedUIFlow.Infrastructure.Commands.FlowActionHelpers
{
    public class FlowActionResult : ActionResult 
    {
        private ApplicationController _appController;
        private FlowService _flowService;
        
        public FlowService FlowService
        {
            get
            {
                return _flowService ?? FlowService.Current;
            }
            set
            {
                _flowService = value;
            }
        }

        public ApplicationController ApplicationController
        {
            get
            {
                return _appController ?? ApplicationController.Current;
            }
            set
            {
                _appController = value;
            }
        }    

        public string State { get; private set; }

        public ManagedFlow Flow { get; private set; }              

        public FlowActionResult(ManagedFlow flow, string state)
        {           
            Flow = flow;
            State = state;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            Flow.ViewData = context.Controller.ViewData;
            Flow.TempData = context.Controller.TempData;
            var newNavigation = FlowService.GetNavigationFor(Flow.Name, Flow.CurrentNavigation, State);
            Flow.SetNavigation(newNavigation);
            ApplicationController.Execute(context.RequestContext, Flow);
        }
    }
}